<script setup lang='ts' name="org-add-user">
import type { FormInstance } from 'element-plus'
import { distributeArea, getCompanyById, getRegionList } from '@fl/api/joint-api'
import { ElButton, ElDialog, ElForm, ElFormItem, ElInput } from 'element-plus'
import { toRefs } from 'vue'
import { useGetProvinceCityCounty } from '@fl/api/supplier'
import { useRule } from './hooks/use-rule'
import axios from 'axios'

const props = defineProps<{
    data: any
    modelValue: boolean
    showId?: string
}>()
const emits = defineEmits(['update:modelValue', 'confirm'])
const { showId } = toRefs(props)
// console.log('🚀 ~ showId:', showId)
const idList = computed(() => {
    return showId.value?.includes(',') ? showId.value.split(',') : [showId.value]
})

const { data, modelValue } = toRefs(props)

const { areaRules } = useRule()

let detail = reactive<any>({})

const form = ref<any>({})
const formRef = ref()

const treeValue = ref<any>([])
const treeData = ref<any>([])
const cascaderRef = ref<any>({})
const cascaderProps = { value: 'areaCode', label: 'areaName', children: 'children', multiple: true, checkStrictly: true }
const areaList = ref([])
const targetProvince = ref<any>({
    name: '湖北省',
    code: '420000000000',
})
// const props = {
//     expandTrigger: 'hover' as const,
// }

function handleChange(value) {
    // console.log('handleChange', value)
    // 获取所有选中节点数组
    const nodes = cascaderRef.value.getCheckedNodes()
    console.log('选中的节点:', nodes)


    areaList.value = nodes.map((node) => {
        const [cityCode, areaCode] = node.pathValues
        const [cityName, areaName] = node.pathLabels

        return ({
            areaCode,
            areaName,
            cityCode,
            cityName,
            companyId: showId.value,
            provinceCode: targetProvince.value.code,
            provinceName: targetProvince.value.name,
        })
    })
}

// 获取省市区地址数据
async function getAreaList() {
    const res = await getRegionList()
    // console.log("🚀 ~ getAreaList ~ res:", res)

    //  treeData.value = res.data
    // targetProvince.value = res.data.find((item: any) => item.name === '湖北省')
    treeData.value = res
}

const { mutateAsync: runGetCompanyById } = useMutation({
    mutationFn: (id: string) => getCompanyById(id),
    onSuccess: async (data) => {
        // console.log('🚀 ~ distributeArea ~ data:', data)
        form.value.area = data.companyAreaAssociationList.map((item: any) => {
            return [item.cityCode, item.areaCode].filter(Boolean)
            // return item.cardName
        })
        areaList.value = data.companyAreaAssociationList.map((item: any) => {
            return ({
                areaCode: item.areaCode,
                areaName: item.areaName,
                cityCode: item.cityCode,
                cityName: item.cityName,
                companyId: showId.value,
            })
        })
    },
})

onMounted(() => {
    getAreaList()
    runGetCompanyById(String(showId.value))
})

const { isPending, mutateAsync: runDistributeArea } = useMutation({
    mutationFn: (data: any) => distributeArea(data),
    onSuccess: async (data) => {
        // console.log('🚀 ~ distributeArea ~ data:', data)
        ElMessage.success('保存成功')
        setTimeout(() => {
            emits('confirm')
            emits('update:modelValue', false)
        }, 1000)
    },
})

async function doSave(formEl: FormInstance | undefined) {
    if (!formEl)
        return
    await formEl.validate((valid, fields) => {
        if (valid) {
            const list = idList.value.reduce((acc, id) => {
                const area = areaList.value.map((item: any) => {
                    return {
                        ...item,
                        provinceCode: targetProvince.value.code,
                        provinceName: targetProvince.value.name,
                        companyId: id,
                    }
                })
                return [...acc, ...area]
            }, [])
            console.log('🚀 ~ list ~ list:', list)

            runDistributeArea(list)
        }
        else {
            console.log('error submit!', fields)
        }
    })
}

function close(formEl: FormInstance | undefined) {
    formEl && formEl.resetFields()
    emits('update:modelValue', false)
}

watch(data, (val: any) => {
    console.log('row', val)
    detail = { ...val }
}, {
    deep: true,
    immediate: true,
})
</script>

<template>
    <ElDialog v-model="modelValue" width="860" class="h-400" :close-on-click-modal="false" title="分配区域"
        @close="close(formRef)">
        <ElForm ref="formRef" :model="form" label-width="auto" class="h-250" :rules="areaRules" label-position="left">
            <ElFormItem label="选择区域" prop="area">
                <el-cascader ref="cascaderRef" class="w-full" v-model="form.area" :props="cascaderProps"
                    :options="treeData" @change="handleChange" />
            </ElFormItem>





        </ElForm>
        <template #footer>
            <div text-center style="width:100%">
                <ElButton @click="close(formRef)">
                    取消
                </ElButton>

                <ElButton type="primary" :loading="isPending" @click="doSave(formRef)">
                    确定
                </ElButton>
            </div>
        </template>
    </ElDialog>
</template>
